package cn.shujuhai.common.config.MyMeta;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("开始插入填充...");
        // 判断是否登录
        if (StpUtil.isLogin()) {
            // 如果登录了，获取当前登录用户的用户名
            this.strictInsertFill(metaObject, "createUser", String.class, StpUtil.getSession().get("username").toString());
        } else {
            // 如果未登录，设置用户名为 "admin"
            this.strictInsertFill(metaObject, "createUser", String.class, "admin");
        }
        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("开始更新填充...");
        // 判断是否登录
        if (StpUtil.isLogin()) {
            // 如果登录了，获取当前登录用户的用户名
            this.strictUpdateFill(metaObject, "updateUser", String.class, StpUtil.getSession().get("username").toString());
        } else {
            // 如果未登录，设置用户名为 "admin"
            this.strictUpdateFill(metaObject, "updateUser", String.class, "admin");
        }
        // 填充更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
    }
}